package com.sduept.nwld.dataserver.controller.feedback;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.entity.core.RecordAttachment;
import com.sduept.bigdata.fault.utils.ExportExcelStyleDefine;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.core.manager.ProblemFeedbackManager;
import com.sduept.bigdata.web.core.model.ProblemFeedback;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.protection.SpecialReportManager;
import com.sduept.utils.DateUtil;
import com.sduept.utils.PingYinUtil;

@Named
@ViewScoped
public class ProblemFeedbackController extends AbstractController {
	@Autowired
	private ExportExcelStyleDefine excelStyleDefine;
	private static final long serialVersionUID = 3238260457685899846L;
	@Autowired
	private CommonDocumentProperties pros;
	@Autowired
	private ProblemFeedbackManager pm;
	@Autowired
	private SpecialReportManager srm;
	
	private List<ProblemFeedback> problemFeedbacks = new ArrayList<>();
	private ProblemFeedback problemFeedback = new ProblemFeedback();
	private ProblemFeedback selectProblemFeedback = new ProblemFeedback();
	private String handleState = "待处理";
	private String selectModule;
	private String solver;
	private Date queryDate1;
	private Date queryDate2;
	/**
	 * 导出的问题反馈
	 */
	private StreamedContent exportFile;
	/**
	 * 附件是否存在
	 */
	private boolean fileExist = false;
	private StreamedContent file;
	private String oid = null;
	private String path = null;
	
	@PostConstruct
	public void init() {
		String feedbackId = getParameter("feedbackId");
		if(StringUtils.isNotEmpty(feedbackId)) {
			problemFeedback = pm.getProblemFeedback(feedbackId);
		}
		problemFeedbacks = pm.queryProblemFeedback(null, null,selectModule, handleState,solver);
	}
	public void preCreate() {
		problemFeedback = new ProblemFeedback();
	}
	
	public void preUpate() {
		problemFeedback = selectProblemFeedback;
	}
	
	public void save() {
		pm.createOrUpdateFeedback(problemFeedback);
		problemFeedbacks = pm.queryProblemFeedback(queryDate1, queryDate2, selectModule, handleState,solver);
		addSuccessMessage("保存成功");
		selectProblemFeedback = new ProblemFeedback();
	}

	public void delete() {
		pm.deleteFeedback(selectProblemFeedback.getId());
		problemFeedbacks = pm.queryProblemFeedback(queryDate1, queryDate2, selectModule, handleState,solver);
		addSuccessMessage("删除成功");
		selectProblemFeedback = new ProblemFeedback();
	}
	
	public List<String> completeProblemCategory(String query) {
		List<String> problemCategories = pm.getAllProblemCategories();
		List<String> results = new ArrayList<String>();
		if (problemCategories.size() > 0) {
        	for (String problemCategory : problemCategories) {
        		if(StringUtils.isNotEmpty(problemCategory)) {
        			String header = PingYinUtil.getPingYinHeader(problemCategory);
        			if (header.contains(query)) {
        				results.add(problemCategory);
        			}
        		}
        	}
		}
		return results;
	}
	/**
	 * 处理当处理人员为"小明、小红、小亮"的情况
	 * @return
	 */
	private Set<String> getAllSingleSolver() {
		List<String> allSolver = pm.getAllSolver();
		Set<String> allSingleSover = new LinkedHashSet<String>();
		for (String solver : allSolver) {
			if(StringUtils.isNotEmpty(solver)) {
				if(solver.contains("、")) {
					String[] singleSolves = solver.split("、");
					for(int i = 0; i<singleSolves.length; i++) {
						allSingleSover.add(singleSolves[i]);
					}
				} else if (solver.contains("，")) {
					String[] singleSolves = solver.split("，");
					for(int i = 0; i<singleSolves.length; i++) {
						allSingleSover.add(singleSolves[i]);
					}
				} else {
					allSingleSover.add(solver);
				}
			}
		}
		allSingleSover.add("暂无处理人员");
		return allSingleSover;
	}

	public List<String> completeSolver(String query) {
		Set<String> allSolver = getAllSingleSolver();
		List<String> results = new ArrayList<String>();
		if (allSolver.size() > 0) {
        	for (String solver : allSolver) {
        		if(StringUtils.isNotEmpty(solver)) {
        			String header = PingYinUtil.getPingYinHeader(solver);
        			if (header.contains(query)) {
        				results.add(solver);
        			}
        		}
        	}
		}
		return results;
	}
	public List<String> completeModule(String query) {
		List<String> modules = pm.getAllModules();
		List<String> results = new ArrayList<String>();
		if (modules.size() > 0) {
        	for (String module : modules) {
        		if(StringUtils.isNotEmpty(module)) {
        			String header = PingYinUtil.getPingYinHeader(module);
        			if (header.contains(query)) {
        				results.add(module);
        			}
        		}
        	}
		}
		return results;
	}
	
	public void search() {
		if(null != queryDate1 && null != queryDate2 && queryDate1.getTime() > queryDate2.getTime()) {
			addErrorMessage("开始时间不能大于结束时间！");
			return;
		}
		problemFeedbacks = pm.queryProblemFeedback(queryDate1, queryDate2,selectModule, handleState,solver);
	}
	
	/**
	 * 导出问题反馈
	 */
	public void exportProblemFeedback() {
		exportFeedback(problemFeedbacks);
		String exportDir = pros.getExportTempPath();
		String fileName = "ProblemFeedback.xlsx";
		InputStream stream;
		try {
			stream = new FileInputStream(new File(exportDir + fileName));
			exportFile = new DefaultStreamedContent(stream, exportDir, fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}	

	/**
	 * 删除附件
	 * @param record
	 */
	public void removeFile(RecordAttachment record) {
		try {
			String removePath = pros.getDocumentPath() + record.getName();
			File f = new File(removePath);
			fileExist = f.exists();
			if (fileExist) {
				fileExist = false;
				f.delete();
			}
			srm.deleteFile(record.getId());
			addSuccessMessage("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("删除失败");
		}
		selectProblemFeedback = null;
	}
	/**
	 * 下载附件
	 * @param id
	 */
	public void fileDownloadView(String id) {
		RecordAttachment recordAttachment = srm.findFileById(id);
		InputStream stream = null;
		file = null;
		try {
			stream = new FileInputStream(pros.getDocumentPath() + recordAttachment.getName());
//			stream = new FileInputStream(pros.getDocumentPath() + recordAttachment.getName());
		} catch (FileNotFoundException e1) {
			addErrorMessage("文件不存在，下载失败！");
			return;
		} finally {
			fileExist = stream != null;
		}
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		try {
			String agent = request.getHeader("User-Agent").toLowerCase();
			if (agent != null && (agent.indexOf("msie") != -1 || (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1))
					|| agent.indexOf("edge") != -1) {
				file = new DefaultStreamedContent(stream, "application/octet-stream", URLEncoder.encode(recordAttachment.getDescription(), "UTF-8"));
			} else {
				file = new DefaultStreamedContent(stream, "application/octet-stream", new String(recordAttachment.getDescription().getBytes("UTF-8"), "ISO8859-1"));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			if (file == null) {
				fileExist = false;
			}
		}
	}
	
	public void preUpLoadFile(String problemFeedbackId) {
 		oid = problemFeedbackId;
 		path = pros.getDocumentPath();
// 		path = pros.getDocumentPath();
	}
	/**
	 * 上传附件
	 * @param event
	 */
	public void handleFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String houzhuiming = file.getFileName().substring(file.getFileName().lastIndexOf("."));
		String id = ObjectId.get().toString();
		String dirFileName = id + houzhuiming;
		String filePath = path;
		if (filePath == null)
			filePath = pros.getDocumentPath() + dirFileName;
//		filePath = pros.getDocumentPath() + dirFileName;
		else
			filePath += dirFileName;
		try {
			FileOutputStream fos = new FileOutputStream(filePath);
			fos.write(file.getContents());
			fos.close();
			RecordAttachment ra = new RecordAttachment();
			ra.setName(dirFileName);
			ra.setDescription(file.getFileName());
			ra.setOid(oid);
			ra.setType("问题反馈附件");
			ra.setUploadDate(new Date());
			ra.setPath(filePath);
			ra.setUploadPerson(getCurrentUser().getName());
			ra = srm.createOrUpdateFile(ra);
		} catch (IOException ee) {
			ee.printStackTrace();
		}
		addSuccessMessage("附件上传成功，请确认");
	}
	
	/**
	 * 根据问题反馈Id获得附件
	 * @param problemFeedbackId
	 * @return
	 */
	public List<RecordAttachment> getFileNamesByProblemFeedbackId(String problemFeedbackId) {
		return pm.getEnclosureByProblemFeedbackId(problemFeedbackId);
	}
	
	public List<ProblemFeedback> getProblemFeedbacks() {
		return problemFeedbacks;
	}
	public void setProblemFeedbacks(List<ProblemFeedback> problemFeedbacks) {
		this.problemFeedbacks = problemFeedbacks;
	}
	public ProblemFeedback getProblemFeedback() {
		return problemFeedback;
	}
	public void setProblemFeedback(ProblemFeedback problemFeedback) {
		this.problemFeedback = problemFeedback;
	}
	public ProblemFeedback getSelectProblemFeedback() {
		return selectProblemFeedback;
	}
	public void setSelectProblemFeedback(ProblemFeedback selectProblemFeedback) {
		this.selectProblemFeedback = selectProblemFeedback;
	}
	public String getHandleState() {
		return handleState;
	}
	public void setHandleState(String handleState) {
		this.handleState = handleState;
	}
	public String getSelectModule() {
		return selectModule;
	}
	public void setSelectModule(String selectModule) {
		this.selectModule = selectModule;
	}
	public String getSolver() {
		return solver;
	}
	public void setSolver(String solver) {
		this.solver = solver;
	}
	public Date getQueryDate1() {
		return queryDate1;
	}
	public void setQueryDate1(Date queryDate1) {
		this.queryDate1 = queryDate1;
	}
	public Date getQueryDate2() {
		return queryDate2;
	}
	public void setQueryDate2(Date queryDate2) {
		this.queryDate2 = queryDate2;
	}
	public StreamedContent getExportFile() {
		return exportFile;
	}
	public void setExportFile(StreamedContent exportFile) {
		this.exportFile = exportFile;
	}
	public boolean isFileExist() {
		return fileExist;
	}
	public void setFileExist(boolean fileExist) {
		this.fileExist = fileExist;
	}
	public StreamedContent getFile() {
		return file;
	}
	public void setFile(StreamedContent file) {
		this.file = file;
	}
	public void exportFeedback(List<ProblemFeedback> problemFeedbacks) {
		String sheetName = "问题反馈";
		String titleName = "问题反馈";
		String exportDir = pros.getExportTempPath();
		String fileName = "ProblemFeedback.xlsx";
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(sheetName);
		String[] columnName = {"序号","模块","问题描述","问题分类","提出时间","提出人员","通知时间","通知人员","计划完成时间","处理时间","处理人员","处理过程","处理情况","原因","备注"};
		// 列宽
		int s = 256 * 10;
		int m = 256 * 15;
		int b = 256 * 20;
		int l = 256 * 35;
		int[] widthes = new int[] {s, m, l, m, m, m, m, m, m, m, m, b, m, b, m};
		int index = 0;
		for (int w : widthes) {
			sheet.setColumnWidth(index++, w);
		}
		// 标题样式
		HSSFCellStyle titlestyle = excelStyleDefine.setTitleStyle(wb);
		// 表头样式
		HSSFCellStyle columnstyle = excelStyleDefine.setColumnStyle(wb);
		// 内容样式
		HSSFCellStyle contentstyle = excelStyleDefine.setContentStyle(wb);

		// 创建第0行 标题行
		HSSFRow row0 = sheet.createRow((int) 0);
		row0.setHeightInPoints(50);// 标题的高度
		// 创建标题第一列
		HSSFCell cell00 = row0.createCell(0);
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnName.length-1)); // 合并第0到第23列
		cell00.setCellValue(titleName);
		cell00.setCellStyle(titlestyle);

		// 创建第1行 表头行
		HSSFRow row1 = sheet.createRow((int) 1);
		row1.setHeightInPoints(37);// 设置表头高度
		// 创建列
		for (int i = 0; i < columnName.length; i++) {
			HSSFCell cell = row1.createCell(i);
			cell.setCellValue(columnName[i]);
			cell.setCellStyle(columnstyle);
		}
		// 创建单元格，并设置值
		creatCell(problemFeedbacks, contentstyle, sheet);
		// 4.将excel导出到文件中
		FileOutputStream out = null;
		File files = new File(exportDir+fileName);
		try {
			files.createNewFile();
			out = new FileOutputStream(files);
			wb.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				wb.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void creatCell(List<ProblemFeedback> problemFeedbacks, HSSFCellStyle contentstyle, HSSFSheet sheet) {
		int i = 0;
		for (ProblemFeedback bean : problemFeedbacks) {
			HSSFRow row = sheet.createRow((int) i + 2);
			// 序号
			HSSFCell cell0 =  row.createCell(0);
			cell0.setCellValue(i+1);
			cell0.setCellStyle(contentstyle);
			// 模块
			HSSFCell cell1 =  row.createCell(1);
			cell1.setCellValue(bean.getModule());
			cell1.setCellStyle(contentstyle);
			// 问题描述
			HSSFCell cell2 =  row.createCell(2);
			cell2.setCellValue(bean.getDescription());
			cell2.setCellStyle(contentstyle);
			// 问题分类
			HSSFCell cell3 =  row.createCell(3);
			cell3.setCellValue(bean.getCategory());
			cell3.setCellStyle(contentstyle);
			// 提出时间
			String proposeTime = DateUtil.getStringDate(bean.getProposeTime(), "yyyy-MM-dd HH:mm:ss");
			HSSFCell cell4 =  row.createCell(4);
			cell4.setCellValue(proposeTime);
			cell4.setCellStyle(contentstyle);
			// 提出人员
			HSSFCell cell5 =  row.createCell(5);
			cell5.setCellValue(bean.getProposer());
			cell5.setCellStyle(contentstyle);
			// 通知时间
			String notifyTime = DateUtil.getStringDate(bean.getNotifyTime(), "yyyy-MM-dd HH:mm:ss");
			HSSFCell cell6 =  row.createCell(6);
			cell6.setCellValue(notifyTime);
			cell6.setCellStyle(contentstyle);
			// 通知人员
			HSSFCell cell7 =  row.createCell(7);
			cell7.setCellValue(bean.getNotifier());
			cell7.setCellStyle(contentstyle);
			// 计划完成时间
			String planFinishTime = DateUtil.getStringDate(bean.getPlanFinishTime(), "yyyy-MM-dd HH:mm:ss");
			HSSFCell cell8 =  row.createCell(8);
			cell8.setCellValue(planFinishTime);
			cell8.setCellStyle(contentstyle);
			// 处理时间
			String solveTime = DateUtil.getStringDate(bean.getSolveTime(), "yyyy-MM-dd HH:mm:ss");
			HSSFCell cell9 =  row.createCell(9);
			cell9.setCellValue(solveTime);
			cell9.setCellStyle(contentstyle);
			// 处理人员
			HSSFCell cell10 =  row.createCell(10);
			cell10.setCellValue(bean.getSolver());
			cell10.setCellStyle(contentstyle);
			// 处理过程
			HSSFCell cell11 =  row.createCell(11);
			cell11.setCellValue(bean.getHandleProcess());
			cell11.setCellStyle(contentstyle);
			// 处理情况
			HSSFCell cell12 =  row.createCell(12);
			cell12.setCellValue(bean.getHandleState());
			cell12.setCellStyle(contentstyle);
			// 原因
			HSSFCell cell13 =  row.createCell(13);
			cell13.setCellValue(bean.getProblemReason());
			cell13.setCellStyle(contentstyle);
			// 备注
			HSSFCell cell14 =  row.createCell(14);
			cell14.setCellValue(bean.getRemark());
			cell14.setCellStyle(contentstyle);
			i++;
		}
	}
}
